package logic

import (
	"book/bookrpc/bookrpc"
	"book/bookrpc/internal/svc"
	"book/models/cache"
	"book/models/mysql"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPasswordLogic) ForgetPassword(in *bookrpc.ForgetPasswordRequest) (*bookrpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册,无法修改密码")
	}

	result, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()

	if result != in.SmsCode {
		return nil, fmt.Errorf("短信验证阿码错误,请重新输入")
	}

	result1, _ := cache.RDB.Get(l.ctx, "captcha"+in.Account).Result()

	if result1 != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证阿码错误,请重新输入")
	}

	if user.Password == in.Password {
		return nil, fmt.Errorf("新密码和原密码一致,无法修改密码")
	}

	if in.Password != in.Newpassword {
		return nil, fmt.Errorf("两次密码输入不一致,无法修改密码")
	}

	user.Password = in.Password

	mysql.DB.Debug().Updates(&user)

	return &bookrpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
